import { cityApi } from "@/api/api";

// 城市模块
const cityModule = {
  // namespaced: true,表示将getters,mutations,actions也加到命名空间里
  namespaced: true,
  state() {
    return {
      cityname: localStorage.getItem("cityname") || "北京",
      cityId: localStorage.getItem("cityId") || 110100,

      // 城市列表数据
      cityList: [],
    };
  },
  getters: {
    // 计算得到热门城市和其他城市
    hotCity(state) {
      return state.cityList[0]; // 对象
    },
    otherCity(state) {
      return state.cityList.slice(1); // 数组
    },
  },
  mutations: {
    changename(state, payload) {
      localStorage.setItem("cityname", payload.name);
      localStorage.setItem("cityId", payload.cityId);
      state.cityname = payload.name;
      state.cityId = payload.cityId;
    },
    // 改变城市列表数据
    getCityList(state, payload) {
      state.cityList = payload.result;
    },
  },
  actions: {
    // 异步获取城市列表
    async asyncGetCityList({ commit }) {
      const res = await cityApi();
      commit("getCityList", res);
    },
  },
};

export default cityModule;
